package com.yidianyanglao.core.interceptor;

import com.yidianyanglao.core.bean.RoleActionBean;
import com.yidianyanglao.core.constant.RequestConstant;
import com.yidianyanglao.core.constant.SessionConstant;
import com.yidianyanglao.core.enums.Code;
import com.yidianyanglao.core.exception.CustomException;
import com.yidianyanglao.core.mapper.RoleMapper;
import com.yidianyanglao.core.util.Log;
import com.yidianyanglao.user.bean.UserBean;
import com.yidianyanglao.user.mapper.UserMapper;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 权限拦截
 */
public class RoleInterceptor implements HandlerInterceptor {
    @Resource
    private RoleMapper rm;

    @Resource
    private UserMapper userMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String action = request.getRequestURI();
        System.out.println("action:"+action);

        RoleActionBean actionBean = rm.getRoleActionBean(action);
        if (actionBean == null) {
            throw new CustomException(Code.ERROR, "非法访问");
        }
        //是否需要session 0不需要 1需要
        if (actionBean.getIsSession() == 0) {
            return true;
        }
        String token = request.getParameter("token");
        if(StringUtils.isEmpty(token)){
            throw new CustomException(Code.ERROR, "token不能为空");
        }
        UserBean userBean = userMapper.getUserInfoByToken(token);
        if(userBean == null){
            throw new CustomException(Code.TIMEOUT, "用户身份过期");
        }
        request.setAttribute("request_user",userBean);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }

}
